﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CefSharp;
using CefSharp.Wpf;
using KeZhou.Models.Instances;
using KeZhou.Views;
using KeZhou.Views.Components.Controls;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;

namespace KeZhou.ViewModels
{
    internal partial class ChooseCityViewModel: ObservableObject
    {
        private static ChooseCityViewModel instance;

        private static string[] timeSlot = { "上午", "下午", "晚上" };

        private ChromiumWebBrowser browser;

        public ChooseCityViewModel()
        {
            iconName = "ArrowUpSLine";
            wishCity = "请选择城市";
            cityDescription = "城市简介生成中...";
            startDate = DateTime.Now;
            endDate = DateTime.Now + TimeSpan.FromDays(1);
            startDateTimeSlot = 0;
            endDateTimeSlot = 0;
            hotel = "还未选择酒店";
            cityImgURL = "";
        }

        public static ChooseCityViewModel Instance
        {
            get
            {
                return instance ?? (instance = new ChooseCityViewModel());
            }
        }

        public void setBrowser(ChromiumWebBrowser browser)
        {
            this.browser = browser;
        }

        [ObservableProperty]
        private string iconName;

        [ObservableProperty]
        private string wishCity;

        [ObservableProperty]
        private string cityDescription;

        [ObservableProperty]
        private DateTime startDate;

        [ObservableProperty]
        private int startDateTimeSlot;

        [ObservableProperty]
        private DateTime endDate;

        [ObservableProperty]
        private int endDateTimeSlot;

        [ObservableProperty]
        private string hotel;

        private double[] hotelLnglat;

        [ObservableProperty]
        private string cityImgURL;

        [RelayCommand]
        private void ChooseCity()
        {
            if (EndDate < StartDate)
            {
                AppDetailView.Instance.showMyMsg("返回时间需要在出发时间之后！");
                return;
            }
            PlanOnBuilding.Instance.cityName = WishCity;
            PlanOnBuilding.Instance.startTime = StartDate.ToString("yyyy-MM-dd") + "-" + StartDateTimeSlot;
            PlanOnBuilding.Instance.endTime = EndDate.ToString("yyyy-MM-dd") + "-" + EndDateTimeSlot;
            PlanOnBuilding.Instance.hotel = Hotel;
            PlanOnBuilding.Instance.hotelLnglat = hotelLnglat;
            AppDetailView.Instance.showMyMsg("设置成功！");
            MainSkeletonViewModel.Instance.changeMode(2);
            MainTwoChooseCity.Instance.Dispatcher.Invoke(new Action(() =>
            {
                MainTwoChooseCity.Instance.closeInfoCard();
            }));
        }


        // 留给JS代码调用
        // JS代码通过该方法返回用户标记的城市
        public void setWish(string cityName)
        {
            WishCity = cityName;

            // 异步请求城市简介
            Task.Run(() =>
            {
               getCityDescription();
            });

            // 显示选择城市提示
            MainTwoChooseCity.Instance.Dispatcher.Invoke(new Action(() =>
            {
                MainTwoChooseCity.Instance.showMessage("选择城市", $"您选择了{cityName}");
            }));
        }

        // JS代码通过该方法返回用户选择的酒店
        public void setHotel(string hotel, double[] lnglat)
        {
            this.Hotel = hotel;
            this.hotelLnglat = lnglat;
            MainTwoChooseCity.Instance.Dispatcher.Invoke(new Action(() =>
            {
                MainTwoChooseCity.Instance.showInfoCard();
            }));
        }

        public void setImgURL(string url)
        {
            CityImgURL = url;
        }

        private async void getCityDescription()
        {
            string api = "https://oa.api2d.net/v1/chat/completions";
            JObject body = new JObject();
            JObject message = new JObject();
            body["model"] = "gpt-3.5-turbo";
            message["role"] = "user";
            message["content"] = $"请从旅游的角度介绍一下{WishCity}，不超过80字。";
            body["messages"] = new JArray { new[] { message } };
            using (HttpClient client = new HttpClient())
            {
                HttpContent content = new StringContent(body.ToString(), Encoding.UTF8, "application/json");
                client.BaseAddress = new Uri(api);
                client.DefaultRequestHeaders
                      .Accept
                      .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "fk209457-KcOAWSG8IpC0g3u54hAyxPRJ89ElG0xx");
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
                request.Content = content;
                try
                {
                    HttpResponseMessage response = await client.SendAsync(request);
                    string responseBody = await response.Content.ReadAsStringAsync();
                    JObject job = JObject.Parse(responseBody);
                    CityDescription = job["choices"][0]["message"]["content"].ToString();
                } catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return;
                }
                
            }
        }
    }
}
